<?php
/**
 * UploadExcelExe.class.php
 * - Upload Excel
 * @author Longlt
 */
class ImportExcel {

	/**
	 * __construct
	 * - Use constructor object
	 */
	public function __construct () {
		// Nothing
	}
	/**
	  * CreateByListControl
	  * - Create excel from template and List Control
	  * @param $name name data control
	  * @param $dataDynamic data dynamic for input cell excel
	  * @param $dataStatic data static for input cell excel
	  * @return void
	 */
	public function getDataMember($fileName) {
		/**
		 * Load Control
		 */
		/** Create a new Reader of the type defined in $inputFileType **/
		$objPHPExcel 	= new PHPExcel();
        $objReader 		= new PHPExcel_Reader_Excel5;

        // Check exist file
		try {
			$objPHPExcel = $objReader->load(Util::pathUpload("temp") . "/" . $fileName);
		}
		catch (Exception $e){
			throw new CHttpException(404,"Không tìm thấy file {$fileName}");
		}

		$objWorksheet 		= $objPHPExcel->getActiveSheet();
		$highestRow 		= $objWorksheet->getHighestRow(); // e.g. 10
		$highestColumn 		= $objWorksheet->getHighestColumn(); // e.g 'F'
		$highestColumnIndex	= PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5

		/*
		 * Convert excel to array
		 */
		$dataFromFile 	= array();
		$listFieldName 	= array('stt', 'fullname', 'cmnd', 'sex', 'email', 'courses_id');

		// Check format file excel
		if (count($listFieldName) != $highestColumnIndex) {
			throw new CHttpException(404,"Format file excel không hợp lệ");
		}

		// Get list data
		for ($row = 3; $row <= $highestRow; ++$row) {
			$temp	= array(
				'fullname'	=> '',
				'cmnd' 		=>'',
				'sex' 		=> '',
				'email' 	=>'',
				'courses_id' =>'',
			);
			$isData		= false;
			for ($col = 0; $col < $highestColumnIndex; $col++) {
				$value	= $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
				if (trim($value) != '') {
					$isData	= true;
					if ($listFieldName[$col] == 'fullname')
						$temp['fullname']	= $value;
					else if ($listFieldName[$col] == 'cmnd')
						$temp['cmnd']	= $value;
					else if ($listFieldName[$col] == 'email')
						$temp['email']	= $value;
					else if ($listFieldName[$col] == 'courses_id')
						$temp['courses_id']	= $value;
					else if ($listFieldName[$col] == 'sex')
						$temp['sex']	= strtolower($value) == 'nam' ? 1 : 0;
				}
			}

			if ($isData) {
				$dataFromFile[$row] = $temp;
			}
		}
		return $dataFromFile;
	}

}
?>